package com.cskaoyan.user.controller;

import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dto.*;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.IRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @program: duolaimall
 * @description: 注册、注册激活
 * @author: zhong
 * @create: 2022-07-30 11:04
 **/
@RestController
@RequestMapping("/user")
public class RegisterController {
    @Autowired
    IKaptchaService kaptchaService;
    @Autowired
    IRegisterService registerService;

    @PostMapping("/register")
    public ResponseData register(@RequestBody Map<String,String> registerForm, HttpServletRequest httpServletRequest) {
        //验证码验证
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setUuid(CookieUtil.getCookieValue(httpServletRequest, "kaptcha_uuid"));
        kaptchaCodeRequest.setCode(registerForm.get("captcha"));
        KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        if (kaptchaCodeResponse.getCode().equals(UserRetCode.KAPTCHA_CODE_ERROR.getCode())) {
            return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        }
        //register
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setEmail(registerForm.get("email"));
        userRegisterRequest.setUserName(registerForm.get("userName"));
        userRegisterRequest.setUserPwd(registerForm.get("userPwd"));
        UserRegisterResponse userRegisterResponse = registerService.register(userRegisterRequest);
        if (userRegisterResponse.getCode().equals(UserRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(userRegisterResponse);
        }
        return new ResponseUtil().setErrorMsg(userRegisterResponse.getMsg());
    }

    @GetMapping("/verify")
    public ResponseData verifyEmail(String uuId,String userName) {
        UserVerifyRequest userVerifyRequest = new UserVerifyRequest();
        userVerifyRequest.setUserName(userName);
        userVerifyRequest.setUuid(uuId);
        UserVerifyResponse userVerifyResponse = registerService.verify(userVerifyRequest);
        if (userVerifyResponse.getCode().equals(UserRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(userVerifyResponse);
        }
        return new ResponseUtil().setErrorMsg(userVerifyResponse.getMsg());
    }

}
